package com.demo.money.controller;

import com.demo.money.kit.Md5Until;
import com.demo.money.model.User;
import com.demo.money.kit.example.UserExample;
import com.demo.money.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Index类<br>
 * index/login.html页面里的请求映射关系
 * <p>
 * <b>常用方法</b>：<br>
 * 1.landingVerification - 登录-验证
 * 2.loginGoToIndex - 登陆成功-重定向到index.html页面
 * <p>
 * <b>全类名</b>:com.demo.money.controller<br>
 * <b>类名</b>:Index<br>
 * <b>创建者</b>:张峰浦<br>
 * <b>创建时间</b>:2020/3/15 13:37<br>
 */
@Controller
public class IndexLoginHtml {
    @Autowired
    private UserService userService;

    /**
     * 登录-验证
     * <p>
     * 接收参数
     * username：账号-String; password：密码-String
     * <p>
     * 密码不能直接验证，需经过加密验证，数据库中没有保存明码的密码
     *
     * @param username 账号
     * @param password 密码
     * @param request  获取session，并保存用户信息
     * @return 响应页面
     */
    @RequestMapping({"user-landingVerification", "user-landingVerification.html"})
    public String landingVerification(String username, String password, HttpServletRequest request) {


        //判断参数有无
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {

            return "index/login";

        }

        //登录操作
        UserExample userExample = new UserExample();

        userExample.createCriteria().andPasswordEqualTo(Md5Until.setMd5(password)).andNameLoginEqualTo(username).andJurisdictionNotEqualTo("C").andValidEqualTo(1);

        List<User> logins = userService.selectByExample(userExample);
        if (logins.size() == 0) {

            return "index/login";

        }

        request.getSession().setAttribute("user", logins.get(0));

        return "redirect:/dashboard.html";
    }

    /**
     * 登陆成功-重定向到index.html页面
     * <p>
     * 解决浏览器表单信息问题
     *
     * @return
     */
    @RequestMapping({"dashboard", "dashboard.html"})
    public String loginGoToIndex() {

        return "index/index";

    }


}
